<?php

namespace App\baocaitong3\SecurityUtil;

use App\baocaitong3\Util\Log;
use type;

/**
 * Company: www.baofu.com
 * @author dasheng(大圣)
 * @date 2018年3月15日
 */
class NewAESUtil
{
    /**
     *
     * @param type $data 待加密的数据
     * @param type $key 密钥
     * @param type $iv 密钥
     * @return type
     * @throws Exception
     */
    public static function AesEncrypt($data, $key)
    {
        if (!function_exists('bin2hex')) {
            function hex2bin($str)
            {
                $sbin = "";
                $len = strlen($str);
                for ($i = 0; $i < $len; $i += 2) {
                    $sbin .= pack("H*", substr($str, $i, 2));
                }
                return $sbin;
            }
        }
        if (!(strlen($key) == 32)) {
            throw new Exception("AES密码长度固定为32位！当前KEY长度为：" . strlen($key));
        }
        $iv = $key;//偏移量与key相同
        //OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING
        $encrypted = openssl_encrypt($data, "AES-128-CBC", $key, OPENSSL_RAW_DATA);
        //$encrypted=mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$key,$data,MCRYPT_MODE_CBC,$iv);
        $data = bin2hex($encrypted);
        return $data;
    }

    /**
     * 解密
     * @param type $sData 待解密的数据
     * @param type $sKey 密钥
     * @param type $iv 密钥
     * @return type
     * @throws Exception
     */
    public static function AesDecrypt($sData, $sKey)
    {
        if (!(strlen($sKey) == 32)) {
            throw new Exception("AES密码长度固定为32位！当前KEY长度为：" . strlen($sKey));
        }
        $Temp_Key = substr($sKey, 0, 16);
        $sIv = $sKey;//偏移量与key相同
        $sData = hex2bin($sData);

        Log::EchoFormat($sData);
        $retrun = openssl_decrypt($sData, "AES-128-ECB", $sKey, OPENSSL_RAW_DATA);
        return $retrun;
    }
}